package com.atguigu.juc.threadlocal;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author yanglin
 * @create 2024-01-30 14:55 星期二
 * description:
 */
public class ThreadLocalDemo {

    /**
     * 需求1：5个销售卖房子，集团高层只关心销售总量的准确统计数
     * 需求2：5个销售卖完随机数房子，各自独享销售额度；
     */
    
    public static void main(String[] args) {
        House house = new House();
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                int size = new Random().nextInt(5) + 1;
                try {
                    for (int j = 1; j <=size; j++) {
                        house.saleHouse();
                        house.saleVolumeByThreadLocal();
                    }
                    System.out.println(Thread.currentThread().getName() + "\t 号销售卖出：" + house.saleVolume.get());
//                System.out.println(size);
                } finally {
                    house.saleVolume.remove();
                }
            }).start();
        }

        try {
            TimeUnit.MILLISECONDS.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(Thread.currentThread().getName() + "\t total = " + house.saleCount);
    }
    
}

class House {
    int saleCount = 0;
    public synchronized void saleHouse() {
        ++saleCount;
    }
    
    //初始化ThreadLocal
//    ThreadLocal<Integer> saleVolume = new ThreadLocal<Integer>(){
//        @Override
//        protected Integer initialValue() {
//            return 0;
//        }
//    };
    
    //java8新增
    ThreadLocal<Integer> saleVolume = ThreadLocal.withInitial(() -> 0);
    
    public void saleVolumeByThreadLocal(){
        saleVolume.set(1 + saleVolume.get());  
    }
}
